package com.fingard.dsp.bank.directbank.chinaums01;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.ICloseOrder;
import com.fingard.dsp.bank.reqrespobj.closeorder.CloseOrderState;
import com.fingard.dsp.bank.reqrespobj.closeorder.ReqCloseOrder;
import com.fingard.dsp.bank.reqrespobj.closeorder.RetAtsCloseOrder;
import com.fingard.text.StringHelper;

import java.util.Date;
import java.util.HashMap;

public class ChinaUMS01CloseOrder extends ChinaUMS01Base implements ICloseOrder {
	@Override
	public RetAtsCloseOrder closeOrder(ReqCloseOrder p_req) {
		if ("CloseH5Order".equals(p_req.reqHeader.transType) || "CloseJSAPIOrder".equals(p_req.reqHeader.transType) ||  "CloseGWOrder".equals(p_req.reqHeader.transType)){
			return closeH5Order(p_req);
		} else {
			return closeOrders(p_req);
		}
	}
	/**
	 * 平常关单
	 * @param p_req
	 * @return
	 */
	public RetAtsCloseOrder closeOrders(ReqCloseOrder p_req) {
		RetAtsCloseOrder retAts = new RetAtsCloseOrder(p_req.reqHeader);
		
		retAts.rdSeq = p_req.rdSeq;
		
		try {
			ActSetItem actItem = getBankConfig().getActSetItemByAny(p_req.ownAct, p_req.merchantId,	p_req.appId, "unifiedorder");
			if (actItem == null) {
				retAts.respCode = "-1";
				retAts.respInfo = "未找到账号[" + p_req.ownAct + "]商户配置信息!";
				retAts.rdSeq = p_req.rdSeq;
				return retAts;
			} 
			
			HashMap<String, String> mapParams = new HashMap<String, String>();
			
			mapParams.put("msgId", ""); /* 消息ID */
			mapParams.put("msgSrc", getMsgSrc()); /* 消息来源 */
			mapParams.put("msgType", "bills.closeQRCode"); /* 消息类型 */
			mapParams.put("requestTimestamp", Format.DateTimeFormat.format(new Date())); /* 报文请求时间，格式yyyy-MM-dd HH:mm:ss */
			mapParams.put("srcReserve", ""); /* 请求系统预留字段 */
			mapParams.put("mid", actItem.merchantId); /* 商户号 */
			mapParams.put("tid", getTerminalNum()); /* 终端号 */
			mapParams.put("instMid", "QRPAYDEFAULT"); /* 业务类型 */
			mapParams.put("qrCodeId", p_req.rdSeq); /* 二维码ID */
			mapParams.put("systemId", ""); /* 系统ID */
			mapParams.put("attachRefund", "true"); /* 是否关闭二维码的同时发起退货  true或false*/
			mapParams.put("signType", "MD5"); /* 签名算法 */
			
			String tmpStrRet = sendUnifiedOrder(mapParams, actItem);
			
			if (StringHelper.hasAnyChar(tmpStrRet)) {
				if (tmpStrRet.contains("{")) {
					JSONObject tmpJsonResp = JSON.parseObject(tmpStrRet);
					
					retAts.respCode = "0";
					retAts.respInfo = tmpJsonResp.getString("errMsg");
					
					String errCode = tmpJsonResp.getString("errCode");
					if ("SUCCESS".equals(errCode)) {
						retAts.closeState = CloseOrderState.Close_Success;
						retAts.respInfo = "订单关闭成功";
					} else {
						retAts.closeState = CloseOrderState.Close_Fail;
						retAts.errorCode = errCode;
						retAts.errorMsg = tmpJsonResp.getString("errMsg");
					}
				} else {
					retAts.respCode = "-1";
					retAts.respInfo = "银联响应数据格式非法";
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = "银联响应为空";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		return retAts;
	}
	/**
	 * 开发接口：1.7. 订单关闭
	 * 
	 * @param p_req
	 * @return
	 */
	public RetAtsCloseOrder closeH5Order(ReqCloseOrder p_req) {
		RetAtsCloseOrder retAts = new RetAtsCloseOrder(p_req.reqHeader);
		retAts.rdSeq = p_req.rdSeq;

		try {
			ActSetItem actItem = this.getBankConfig().getActSetItem(p_req.ownAct, "unifiedorder");
            if (actItem != null) {
            	
				HashMap<String, String> closeH5 = new HashMap<String, String>();
				
				closeH5.put("msgId", ""); /* 消息ID */
				closeH5.put("requestTimestamp", Format.DateTimeFormat.format(new Date())); /* 报文请求时间，格式yyyy-MM-dd HH:mm:ss */
				closeH5.put("merOrderId", p_req.rdSeq);
				closeH5.put("mid", actItem.merchantId); /* 商户号 */
				closeH5.put("tid", actItem.termId); /* 终端号 */
				closeH5.put("instMid", "YUEDANDEFAULT"); /* 业务类型 */
                String bankFrontUrl = "";
                if ("CloseH5Order".equals(p_req.reqHeader.transType)) {
                    bankFrontUrl = bankFront.getUrl("closeH5Pay");
                } else if ("CloseJSAPIOrder".equals(p_req.reqHeader.transType)) {
                    bankFrontUrl = bankFront.getUrl("closeJSAPI");
                } else if ("CloseGWOrder".equals(p_req.reqHeader.transType)) {
                    bankFrontUrl = actItem.serverURLMap.get("closeSZGWPay");
                    if (StringHelper.isNullOrEmpty(bankFrontUrl)) {
                        bankFrontUrl = bankFront.getUrl("closeGWPay");
                    }
                }
                if (StringHelper.isNullOrEmpty(bankFrontUrl)) {
                    retAts.respCode = "-1";
                    retAts.respInfo = "发送银行的请求地址为空，请检查bankFront和config中对应配置！";
                }
				String tmpStrRet = querySend(bankFrontUrl, JSON.toJSONString(closeH5), actItem);
	            
	            if (StringHelper.hasAnyChar(tmpStrRet)) {
	                if (tmpStrRet.contains("{")) {
	                	JSONObject tmpJsonResp = JSON.parseObject(tmpStrRet);
	                	
	                	retAts.respCode = "0";
						retAts.respInfo = tmpJsonResp.getString("errMsg");
	                	
	                	String errCode = tmpJsonResp.getString("errCode");
	                	String status = tmpJsonResp.getString("status"); 
	                    if ("TRADE_CLOSED".equals(status)) {
	                    	retAts.closeState = CloseOrderState.Close_Success;
							retAts.respInfo = "订单关闭成功";
	                    } else {
	                    	retAts.closeState = CloseOrderState.Close_Fail;
							retAts.errorCode = errCode;
							retAts.errorMsg = tmpJsonResp.getString("errMsg");
	                    }
	                } else {
	                	retAts.respCode = "-1";
	                	retAts.respInfo = "银联响应数据格式非法";
	                }
	            } else {
	            	retAts.respCode = "-1";
	            	retAts.respInfo = "银联响应为空";
	            } 
            }else {
                retAts.respCode = "-1";
                retAts.respInfo = "未找到账号[" + p_req.ownAct + "]商户配置信息!";
            }
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		return retAts;
	}
}
